"""
管理后台 - 认证接口
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from pydantic import BaseModel
from app.core.database import get_db
from app.core.security import create_access_token, verify_password
from app.models.user import User
from app.schemas.common import ApiResponse
from loguru import logger

router = APIRouter(prefix="/auth", tags=["管理后台-认证"])


class AdminLoginRequest(BaseModel):
    """管理员登录请求"""
    phone: str
    password: str


class AdminLoginResponse(BaseModel):
    """管理员登录响应"""
    token: str
    userInfo: dict


@router.post("/login", response_model=ApiResponse[AdminLoginResponse])
async def admin_login(
    request: AdminLoginRequest,
    db: Session = Depends(get_db)
):
    """
    管理员登录
    只允许 super_admin 和 city_manager 登录
    """
    logger.info(f"🔐 管理员登录尝试: {request.phone}")
    
    # 查询用户
    user = db.query(User).filter(User.phone == request.phone).first()
    if not user:
        logger.warning(f"❌ 用户不存在: {request.phone}")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="手机号或密码错误"
        )
    
    # 验证密码
    if not verify_password(request.password, user.password_hash):
        logger.warning(f"❌ 密码错误: {request.phone}")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="手机号或密码错误"
        )
    
    # 检查角色权限
    user_role = getattr(user, 'role', 'user')
    if user_role not in ['super_admin', 'city_manager']:
        logger.warning(f"❌ 权限不足: {request.phone}, role: {user_role}")
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有管理后台访问权限"
        )
    
    # 生成 Token
    token = create_access_token(data={"sub": user.id})
    
    # 返回用户信息
    user_info = user.to_dict()
    user_info['role'] = user_role
    
    logger.success(f"✅ 管理员登录成功: {request.phone}, role: {user_role}")
    
    return ApiResponse(data={
        "token": token,
        "userInfo": user_info
    })


@router.post("/logout", response_model=ApiResponse[str])
async def admin_logout():
    """管理员登出"""
    # Token 由前端清除，后端只需返回成功
    return ApiResponse(message="登出成功")

